/**
 * 添加企业的相关附件(方案)，进度，项目--js
 */
var ent_associated_add = {
	_ID : null,
	_OBJ : null,
	fileArrayPlan:[],
	fileArrayPro:[],
	planObj:null,
	proObj:null,
	fileSplitSize:1024 * 1024 * 10,
	/**
	 * 用户数据集
	 */
	userData : [],
	/**
	 * 下拉多选
	 */
	mySelectCheck : null,
	/**
	 * 单选
	 */
	mySelectRadio : null,
	/**
	 * 初始化，包括初始化日期选择插件
	 */
	init : function() {
		ent_associated_add.initDatePicker();
		ent_associated_add.loadUseData();
		ent_associated_add.initMySelect();
	},
	/**
	 * 在企业保存后初始化，包括保存id，企业对象，初始化文件上传
	 * 保存企业后调用此方法才是真正可以添加方案，进度和项目了
	 * @param obj
	 */
	initAfterEntSaved : function(obj) {
		ent_associated_add._ID = obj.id;
		ent_associated_add._OBJ = obj;
		ent_associated_add.initFileUpload();
	},
	/**
	 * 加载可用用户
	 * 1、可以，0、不可用
	 */
	loadUseData : function() {
		$.ajax({
			url : "/crm/user/loadUserByIsUse",
			dataType : "json",
			async : false, // 同步
			data : {
				isUse:1
			}, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				ent_associated_add.userData = data;
			},
			error : function() {
			}
		})
	},
	/**
	 * 初始化项目的选择框
	 */
	initMySelect : function() {
		ent_associated_add.mySelectCheck = $("#mySelect").mySelect({
			mult : true, // true为多选,false为单选
			option : ent_associated_add.userData,
			onChange : function(res) { // 选择框值变化返回结果
				//console.log(res)
				//console.log(mySelect.getResultDatas());
			}
		});

		ent_associated_add.mySelectRadio = $("#mySelect2").mySelect({
			mult : false,//true为多选,false为单选
			option : ent_associated_add.userData,
			onChange : function(res) {//选择框值变化返回结果
				//console.log(res)
				//console.log(mySelect.getResultDatas());
			}
		});
	},
	/**
	 * 日期选择器初始化
	 */
	initDatePicker : function() {
		laydate.render({
			elem: '#beginTime' //开始时间
		});
		laydate.render({
			elem: '#nextStepTime' //开始日期
		});
		laydate.render({
			elem: '#nextStepTimeId' //下一节点时间
		});
	},
	/**
	 * 展示添加方案框
	 */
	addPlan : function() {
		if(ent_associated_add._ID === null || ent_associated_add._OBJ === null) {
			layer.msg("请先保存企业.");
			return false;
		}
		$(".add_file").hide();
		$(".add_plan").show();
	},
	/**
	 * 展示添加进度框
	 */
	addProgress : function() {
		if(ent_associated_add._ID === null || ent_associated_add._OBJ === null) {
			layer.msg("请先保存企业.");
			return false;
		}
		$(".add_pro_file").hide();
		$(".add_pro").show();
	},
	/**
	 * 初始化上传
	 */
	initFileUpload:function() {
		//上传方案初始化
		$("#UploadPlanFile").on("change", function() {
			var files = this.files;
			$.each(files, function(key, val) {
				var file = val;
				var name = file.name;
				var size = file.size, type = file.type || "", id =(file.lastModified + "").replace(/\W/g, '') + size + type.replace(/\W/g, '') + name.replace(/\W/g, '');
				if (!limitFileType(name)) {// 文件内容为空
					layer.alert("不接受此文件类型！");
					return;
				}else if (size==0) {// 文件内容为空
					layer.alert("文件内容不存在！");
					return;
				}else if (size > 1024 * 1024 * 1024 * 2) {// 大于2G
					layer.alert("文件过大！");
					return;
				} else if (ent_associated_add.fileArrayPlan.indexOf(id) != -1) {
					layer.alert("文件已存在！");
					return;
				}else{
					$("#UploadPlanFile").parents("dl").next().find("input").val(name);
					ent_associated_add.fileArrayPlan.push(id);
					ent_associated_add.fileArrayPlan[id] = file;
				}
			});
		});
		//上传进度初始化
		$("#UploadProgressFile").on("change", function() {
			var files = this.files;
			$.each(files, function(key, val) {
				var file = val;
				var name = file.name;
				var size = file.size, type = file.type || "", id =(file.lastModified + "").replace(/\W/g, '') + size + type.replace(/\W/g, '') + name.replace(/\W/g, '');
				if (size==0) {// 文件内容为空
					layer.alert("文件内容不存在！");
					return;
				}else if (size > 1024 * 1024 * 1024 * 2) {// 大于2G
					layer.alert("文件过大！");
					return;
				} else if (ent_associated_add.fileArrayPro.indexOf(id) != -1) {
					layer.alert("文件已存在！");
					return;
				} else {
					$("#UploadProgressFile").parents("dl").next().find("input").val(name);
					ent_associated_add.fileArrayPro.push(id);
					ent_associated_add.fileArrayPro[id] = file;
				}
			});
		});
	},
	/**
	 * 保存方案
	 */
	savePlan : function(_this) {
		if(ent_associated_add._ID === null || ent_associated_add._OBJ === null) {
			layer.msg("请先保存企业.");
			return false;
		}
		// 保存数据
		var listData = [];
		ent_associated_add.planObj={};
		var accTitle=$(".add_plan").find(".accessoryName").val();
		if (accTitle == undefined || accTitle.trim().length == 0) {
			layer.alert("未填写附件名称！");
			return;
		}
		var planDescribe=$(".add_plan").find(".planDescribe").val();
		ent_associated_add.planObj.accTitle = accTitle;
		ent_associated_add.planObj.planDescribe = planDescribe;
		ent_associated_add.planObj.dataUuid=ent_associated_add._OBJ.uuid;
		ent_associated_add.planObj.dataName=ent_associated_add.data.obj.entName;
		ent_associated_add.planObj.accType=1;
		//上传中
		var loading = layer.load(0, { //icon支持传入0-2
		    shade: [0.5, 'gray'], //0.5透明度的灰色背景
		    content: '文件上传中',
		    success: function (layero) {
		        layero.find('.layui-layer-content').css({
		            'padding-top': '39px',
		            'width': '80px'
		        });
		    }
		});
		var uploadPath="project//"+ent_associated_add._OBJ.uuid+"//plan"
		//上传文件
		ent_associated_add.funFileUpload(ent_associated_add.fileArrayPlan[0],ent_associated_add.fileArrayPlan,uploadPath,"acessory");
		listData.push(ent_associated_add.planObj);
		$.ajax({
			url : "/crm/accessory/saveAccessorys",
			dataType : "json",
			async : false,
			data : JSON.stringify(listData),
			contentType : "application/json;charset=UTF-8",
			type : "post",
			success : function(data) {
				layer.close(loading);
				if (data.status) {
					ent_associated_add.resetPlan();
					$(".add_file").show();
					$(".add_plan").hide();
					layer.alert(data.count+"条记录保存成功！"+data.info);
					ent_associated_add.findAccessory();
				} else {
					layer.alert('保存失败！'+data.info);
				}
			},
			error : function() {

			}
		});
	},
	resetPlan:function(){
		ent_associated_add.planObj = null;
		ent_associated_add.fileArrayPlan=[];
		$(".add_plan").find(".accessoryName").val("");
		$(".add_plan").find(".planDescribe").val("");
		$("#UploadPlanFile").parents("dl").next().find("input").val("");
	},
	/**
	 * 保存进度
	 */
	saveProgress : function(_this) {
		if(ent_associated_add._ID === null || ent_associated_add._OBJ === null) {
			layer.msg("请先保存企业.");
			return false;
		}
		// 保存数据
		ent_associated_add.proObj={};
		var listData = [];
		var proTitle=$(".add_pro").find(".proTitle").val();
		if (proTitle == undefined || proTitle.trim().length == 0) {
			layer.alert("未填写进度标题！");
			return;
		}
		var nextStepTime=$(".add_pro").find(".nextStepTime").val();
		var proDescribe=$(".add_pro").find(".proDescribe").val();
		ent_associated_add.proObj.proTitle = proTitle;
		ent_associated_add.proObj.nextStepTime = nextStepTime;
		ent_associated_add.proObj.proDescribe = proDescribe;
		ent_associated_add.proObj.dataUuid=ent_associated_add._OBJ.uuid;
		ent_associated_add.proObj.dataName=ent_associated_add.data.obj.entName;
		ent_associated_add.proObj.proType=1;
		//上传中	
		var loading = layer.load(0, { //icon支持传入0-2
		    shade: [0.5, 'gray'], //0.5透明度的灰色背景
		    content: '文件上传中',
		    success: function (layero) {
		        layero.find('.layui-layer-content').css({
		            'padding-top': '39px',
		            'width': '80px'
		        });
		    }
		});
		var uploadPath="project//"+ent_associated_add._OBJ.uuid+"//progress"
		//上传文件
		ent_associated_add.funFileUpload(ent_associated_add.fileArrayPro[0],ent_associated_add.fileArrayPro,uploadPath,"progress");
		listData.push(ent_associated_add.proObj);
		$.ajax({
			url : "/crm/progress/saveProgresss",
			dataType : "json",
			async : false,
			data : JSON.stringify(listData),
			contentType : "application/json;charset=UTF-8",
			type : "post",
			success : function(data) {
				layer.close(loading);
				if (data.status) {
					ent_associated_add.resetPro();
					$(".add_pro_file").show();
					$(".add_pro").hide();
					layer.alert(data.count+"条记录保存成功！"+data.info);
					ent_associated_add.findProgress();
				} else {
					layer.alert('保存失败！'+data.info);
				}
			},
			error : function() {

			}
		});
	},
	resetPro:function(){
		ent_associated_add.proObj = null;
		ent_associated_add.fileArrayPro=[];
		$(".add_pro").find(".proTitle").val("");
		$(".add_pro").find(".nextStepTime").val("");
		$(".add_pro").find(".proDescribe").val("");
		$("#UploadProgressFile").parents("dl").next().find("input").val("");
	},
	/**
	 * 检索项目方案和进度获取条件
	 */
	getPPParam : function() {
		var obj = {};
		obj.pageIndex = 1;
		obj.pageSize = 1000;
		var searchWord = {};
		searchWord.dataUuid = ent_associated_add._OBJ.uuid;//  查询字段
		searchWord.entUuid = ent_associated_add._OBJ.uuid;//  查询字段
		obj.conditions = JSON.stringify(searchWord);
		return obj;
	},
	/**
	 * 查询项目进度列表
	 */
	findProgress : function() {
		$.ajax({
			url : "/crm/progress/findBySpec", 
			dataType : "json", 
			async : true,
			data : ent_associated_add.getPPParam(),
			type : "post",
			success : function(data) {
				if(data.total>0){
					var html='<tr class="first_tr"><th style="width:20%;">进度标题</th><th style="width:30%;">进度描述</th><th style="width:10%;">下一节点时间</th><th style="width:15%;">上传时间</th><th style="width:10%;">附件</th><th style="width:10%;">下载</th></tr>';
					$(data.rows).each(function(key,val){
						if(key%2==0){
							html+='<tr>';
						}else{
							html+='<tr class="tr_shade">';
						}
						html+='<td>'+val.proTitle+'</td>';
						html+='<td>'+val.proDescribe+'</td>';
						html+='<td>'+val.nextStepTime+'</td>';
						html+='<td>'+val.createTime+'</td>';
						if(isBlank(val.proFilePath)){
							html+='<td>--</td>';
							html+='<td>--</td>';
						}else{
							html+='<td>'+val.proFilePath.substring(val.proFilePath.lastIndexOf("/") + 1)+'</td>';
							html+='<td><a onclick="preview(\''+val.proFilePath+'\',1)">预览</a><a onclick="downloadServer(\''+val.proFilePath+'\',1)">下载</a></td>';
						}
						html+='</tr>';
					});
					$("#progressTable").html(html);
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0});
			}
		});
	},
	/**
	 * 查询项目方案列表
	 */
	findAccessory : function() {
		$.ajax({
			url : "/crm/accessory/findBySpec", 
			dataType : "json", 
			async : true,
			data : ent_associated_add.getPPParam(),
			type : "post",
			success : function(data) {
				if(data.total>0){
					var html='<tr class="first_tr"><th style="width:20%;">附件名称</th><th style="width:45%;">附件描述</th><th style="width:15%;">上传时间</th><th style="width:10%;">附件</th><th style="width:10%;"></th></tr>';
					$(data.rows).each(function(key,val){
						if(key%2==0){
							html+='<tr>';
						}else{
							html+='<tr class="tr_shade">';
						}
						html+='<td>'+val.accTitle+'</td>';
						html+='<td>'+val.planDescribe+'</td>';
						html+='<td>'+val.createTime+'</td>';
						if(isBlank(val.accFilePath)){
							html+='<td>--</td>';
							html+='<td>--</td>';
						}else{
							html+='<td>'+val.accFilePath.substring(val.accFilePath.lastIndexOf("/") + 1)+'</td>';
							html+='<td><a onclick="preview(\''+val.accFilePath+'\',1)">预览</a><a onclick="downloadServer(\''+val.accFilePath+'\',1)">下载</a></td>';
						}
						html+='</tr>';
					});
					$("#planTable").html(html);
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0});
			}
		});
	},
	/**
	 * 重置项目的输入框
	 */
	resetProjectForm : function() {
		$("#ent_associated_project_div input").val(""); // 清空输入框
		$("#ent_associated_project_div #proRemarks").val(""); 
		$("#ent_associated_project_div .mySelect").empty();
		ent_associated_add.initMySelect()
	},
	/**
	 * 保存新增的项目
	 */
	saveAddProject : function(_this) {
		if(ent_associated_add._ID === null || ent_associated_add._OBJ === null) {
			layer.msg("请先保存企业.");
			return false;
		}
		var proName = $("#proName").val(); // 项目名称
		var beginTime = $("#beginTime").val(); // 开始时间
		var nextStepTime = $("#nextStepTime").val(); // 下一节点时间
		var proRemarks = $("#proRemarks").val();

		// 必填项的判断
		if(isBlank(proName)) {
			layer.msg("请输入项目名称");
			return false;
		}
		if(isBlank(beginTime)) {
			layer.msg("请选择开始时间");
			return false;
		}
		if(isBlank(nextStepTime)) {
			layer.msg("请选择开始下一节点时间");
			return false;
		}

		var obj = {};
		obj.proName = proName;
		obj.beginTime = beginTime;
		obj.nextStepTime = nextStepTime;
		obj.proRemarks=proRemarks;
		// 设置和企业的关联关系
		obj.entUuid = ent_associated_add._OBJ.uuid;
		obj.entName = ent_associated_add._OBJ.entName;
		// 责任人相关处理
		if(ent_associated_add.mySelectRadio.getResultDatas().length === 1) {
			obj.userUuid = ent_associated_add.mySelectRadio.getResultDatas()[0].value;
			obj.userName = ent_associated_add.mySelectRadio.getResultDatas()[0].name;
		}
		// 小组成员的相关处理
		var teamMembersUuids = [];
		var teamMembersNames = [];
		$.each(ent_associated_add.mySelectCheck.getResultDatas(), function(k, v) {
			teamMembersUuids.push(v.value);
			teamMembersNames.push(v.name);
		});
		obj.teamMembersUuids = teamMembersUuids.join(",");
		obj.teamMembersNames = teamMembersNames.join(",");

		$.ajax({
			url : "/crm/project/save",
			dataType : "json",
			data : obj,
			type : "post",
			success : function(data) {
				if(data.status) {
					layer.alert(data.info, {icon: 1, closeBtn: 0}, function(index) {
						ent_associated_add.findProject();
						ent_associated_add.resetProjectForm(); // 清空输入框
						layer.close(index);
					});
				} else {
					layer.msg(data.info, {icon: 2, closeBtn: 0});
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0});
			}
		});
	},
	/**
	 * 查询项目
	 */
	findProject : function() {
		$.ajax({
			url : "/crm/project/findBySpec",
			dataType : "json",
			data : ent_associated_add.getPPParam(),
			type : "post",
			success : function(data) {
				if(data.total > 0) {
					var html = '<tr class="first_tr">'+
						 '<th style="width: 20%;">项目名称</th>' +
	                     '<th style="width: 10%;">负责人</th>' +
	                     '<th style="width: 25%;">小组成员</th>' +
	                     '<th style="width: 15%;">开始时间</th>' +
	                     '<th style="width: 15%;">开始时间</th>' +
	                     '<th style="width: 25%;">项目描述</th>' +
						'</tr>';
					$(data.rows).each(function(key, val) {
						if(key%2 === 0) {
							html += '<tr>';
						} else {
							html += '<tr class="tr_shade">';
						}
						html += '<td>' + val.proName + '</td>';
                        html += '<td>' + val.userName + '</td>';
                        html += '<td>' + val.teamMembersNames + '</td>';
                        html += '<td>' + val.beginTime + '</td>';
                        html += '<td>' + val.nextStepTime + '</td>';
                        html += '<td>' + val.proRemarks + '</td>';
						html += '</tr>';
					});
					$("#projectTable").html(html);
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0});
			}
		});
	},
	/**
	 * 单文件上传
	 */
	funFileUpload:function(fileid,fileArray,uploadPath,fileType,onsuccess, onerror, onpause) {
		var file = fileArray[fileid], now = performance.now();
		if (!fileid || !file)
			return;
		onsuccess = onsuccess || function() {
			ent_associated_add.funFileUpload(fileArray[0],fileArray,uploadPath,fileType);
		};

		onerror = onerror || function() {
			ent_associated_add.funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath,fileType);
		};
		onpause = onpause || function() {
			ent_associated_add.funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath,fileType);
		};
		if (file.flagPause == true) {
			onpause.call(fileid);
			return;
		}
		// objStateElement.wait(fileid);
		// 文件分割上传
		// 文件大小和分割起点
		// 注释的是本地存储实现
		var size = file.size, start = localStorage[fileid] * 1 || 0;
		// start = $("filelist_" + fileid).filesize;
		if (size == start) {
			// 已经传过了
			fileArray.shift();
			if (delete fileArray[fileid])
			// objStateElement.success(fileid, now);
			// 回调
			onsuccess.call(fileid, {});
			localStorage.clear();
			return;
		}

		var funFileSize = function() {
			if (file.flagPause == true) {
				onpause.call(fileid);
				return;
			}
			var data = new FormData();
			var name = file.name.replace(/[\@\#\$\%\^\&\*\{\}\:\"\L\<\>\?\ ]/g ,'');
			data.append("fileName", encodeURIComponent(name));
			data.append("fileid", fileid);
			data.append("myFile", file.slice(start, start + ent_associated_add.fileSplitSize));
			data.append("start", start + "");
			data.append("flag",(start + ent_associated_add.fileSplitSize)>=size?"COMPLETE":"UPLOAD");
			data.append("uploadPath",uploadPath);
			var p = "?name=" + encodeURIComponent(name) + "&fileid" + fileid + "&start" + start;
			// XMLHttpRequest 2.0 请求
			var xhr = new XMLHttpRequest();
			xhr.open("post", "/crm/fileUpload", false);
			// .setRequestHeader("X_Requested_With",
			// location.href.split("/")[5].replace(/[^a-z]+/g,"$"));
			// xhr.setRequestHeader("Content-type", "multipart/form-data");
			// 上传进度中
			xhr.upload.addEventListener("progress", function(e) {
				// objStateElement.backgroundSize(fileid, (e.loaded + start) / size
				// * 100);
			}, false);
			// ajax成功后
			xhr.onreadystatechange = function(e) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						try {
							var json = JSON.parse(xhr.responseText);
							temp = 2;
						} catch (e) {
							// objStateElement.error(fileid);
							return;
						}
						// var json = JSON.parse(xhr.responseText);
						if (!json || !json.succ) {
							// objStateElement.error(fileid);
							onerror.call(fileid, json);
							return;
						}

						if (start + ent_associated_add.fileSplitSize >= size) {
							// 超出，说明全部分割上传完毕
							// 上传队列中清除者一项
							fileArray.shift();
							if (delete fileArray[fileid])
							// objStateElement.success(fileid, now);
							// 回调
							onsuccess.call(fileid, json);
							filePath = json.data.savePath;
							if(fileType=="acessory"){
								ent_associated_add.planObj.accFilePath = filePath;
							}else if(fileType=="progress"){
								ent_associated_add.proObj.proFilePath = filePath;
							}
							localStorage.clear();
						} else {
							// 尚未完全上传完毕
							// 改变下一部分文件的起点位置
							start += ent_associated_add.fileSplitSize;
							// 存储上传成功的文件点，以便出现意外的时候，下次可以断点续传
							localStorage.setItem(fileid, start + "");
							// 上传下一个分割文件
							funFileSize();

						}
					} else {
						// objStateElement.error(fileid);
					}
				}
			};

			xhr.send(data);
		};
		// 文件分割上传开始
		funFileSize();
	}
};